'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { 
  getTabToken, 
  getAllTabTokens, 
  hasValidTabToken
} from '@/lib/cache'

export default function TabIsolationDemoPage() {
  const [currentTabId, setCurrentTabId] = useState<string>('')
  const [allTabTokens, setAllTabTokens] = useState<Array<{ tabId: string; token: string | null; isCurrent: boolean }>>([])
  const [currentToken, setCurrentToken] = useState<string | null>(null)
  const [hasToken, setHasToken] = useState(false)

  // 刷新页面信息
  const refreshPageInfo = () => {
    // 获取当前标签页ID（通过模拟调用）
    const tabId = getCurrentTabId()
    setCurrentTabId(tabId)
    
    // 获取当前token
    const token = getTabToken()
    setCurrentToken(token)
    setHasToken(hasValidTabToken())
    
    // 获取所有标签页token信息
    const allTokens = getAllTabTokens()
    setAllTabTokens(allTokens)
  }

  // 添加测试token
  const handleAddTestToken = () => {
    const testToken = `test_token_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`
    localStorage.setItem(`tab_token_${currentTabId}`, testToken)
    refreshPageInfo()
  }

  // 清理当前标签页token
  const handleClearCurrentToken = () => {
    localStorage.removeItem(`tab_token_${currentTabId}`)
    refreshPageInfo()
  }

  // 清理所有标签页token
  const handleClearAllTokens = () => {
    // 清理所有标签页token
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i)
      if (key && key.startsWith('tab_token_')) {
        localStorage.removeItem(key)
      }
    }
    refreshPageInfo()
  }

  useEffect(() => {
    refreshPageInfo()
    
    // 监听storage变化
    const handleStorageChange = () => {
      refreshPageInfo()
    }
    
    window.addEventListener('storage', handleStorageChange)
    
    return () => {
      window.removeEventListener('storage', handleStorageChange)
    }
  }, [])

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">标签页Token隔离演示</h1>
        <Button onClick={refreshPageInfo} variant="outline">
          刷新信息
        </Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 当前标签页信息 */}
        <Card>
          <CardHeader>
            <CardTitle>当前标签页信息</CardTitle>
            <CardDescription>当前标签页的详细信息</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex justify-between">
              <span>标签页ID:</span>
              <Badge variant="outline" className="font-mono text-xs">
                {currentTabId || '未生成'}
              </Badge>
            </div>
            <div className="flex justify-between">
              <span>当前Token:</span>
              <Badge variant={hasToken ? "default" : "secondary"}>
                {hasToken ? '已设置' : '未设置'}
              </Badge>
            </div>
            {currentToken && (
              <div className="bg-gray-100 p-2 rounded text-xs font-mono break-all">
                {currentToken}
              </div>
            )}
          </CardContent>
        </Card>

        {/* 操作按钮 */}
        <Card>
          <CardHeader>
            <CardTitle>操作</CardTitle>
            <CardDescription>管理当前标签页的token</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <Button onClick={handleAddTestToken} className="w-full" variant="outline">
              添加测试Token
            </Button>
            <Button onClick={handleClearCurrentToken} className="w-full" variant="outline">
              清理当前Token
            </Button>
            <Button onClick={handleClearAllTokens} className="w-full" variant="destructive">
              清理所有Token
            </Button>
          </CardContent>
        </Card>
      </div>

      {/* 所有标签页Token信息 */}
      <Card>
        <CardHeader>
          <CardTitle>所有标签页Token</CardTitle>
          <CardDescription>
            显示所有标签页的token信息（包括其他标签页）
          </CardDescription>
        </CardHeader>
        <CardContent>
          {allTabTokens.length === 0 ? (
            <div className="text-center text-gray-500 py-8">
              暂无标签页Token信息
            </div>
          ) : (
            <div className="space-y-3">
              {allTabTokens.map((tabInfo) => (
                <div 
                  key={tabInfo.tabId} 
                  className={`p-3 rounded border ${
                    tabInfo.isCurrent ? 'border-blue-500 bg-blue-50' : 'border-gray-200'
                  }`}
                >
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <Badge variant={tabInfo.isCurrent ? "default" : "secondary"}>
                        {tabInfo.isCurrent ? '当前标签页' : '其他标签页'}
                      </Badge>
                      <span className="text-sm font-mono text-gray-600">
                        {tabInfo.tabId}
                      </span>
                    </div>
                    <Badge variant={tabInfo.token ? "default" : "secondary"}>
                      {tabInfo.token ? '有Token' : '无Token'}
                    </Badge>
                  </div>
                  {tabInfo.token && (
                    <div className="bg-gray-100 p-2 rounded text-xs font-mono break-all">
                      {tabInfo.token}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 使用说明 */}
      <Card>
        <CardHeader>
          <CardTitle>使用说明</CardTitle>
          <CardDescription>如何测试标签页Token隔离功能</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="space-y-2">
            <h4 className="font-semibold">测试步骤：</h4>
            <ol className="list-decimal list-inside space-y-1 text-sm">
              <li>在当前标签页添加一个测试Token</li>
              <li>打开新的标签页，访问相同页面</li>
              <li>在新标签页添加另一个测试Token</li>
              <li>观察两个标签页的Token是否独立</li>
              <li>切换标签页，验证Token是否正确显示</li>
            </ol>
          </div>
          
          <div className="space-y-2">
            <h4 className="font-semibold">预期结果：</h4>
            <ul className="list-disc list-inside space-y-1 text-sm">
              <li>每个标签页都有独立的Token</li>
              <li>切换标签页时Token不会混乱</li>
              <li>清理Token只影响当前标签页</li>
              <li>可以同时登录不同的账号</li>
            </ul>
          </div>
          
          <div className="bg-blue-50 p-3 rounded text-sm">
            <strong>💡 提示：</strong>
            这个功能解决了在同一个浏览器中同时登录多个账号时Token混乱的问题。
            每个标签页都有独立的认证状态，互不影响。
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

// 辅助函数：获取当前标签页ID（模拟实现）
function getCurrentTabId(): string {
  let tabId = sessionStorage.getItem('current_tab_id')
  if (!tabId) {
    tabId = `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    sessionStorage.setItem('current_tab_id', tabId)
  }
  return tabId
}
